package com.wjx.zk

import org.apache.curator.framework.CuratorFramework
import org.apache.curator.framework.CuratorFrameworkFactory
import org.apache.curator.framework.recipes.leader.CancelLeadershipException
import org.apache.curator.framework.recipes.leader.LeaderSelector
import org.apache.curator.framework.recipes.leader.LeaderSelectorListener
import org.apache.curator.framework.state.ConnectionState
import org.apache.curator.retry.ExponentialBackoffRetry
import java.time.LocalDateTime

fun main(args: Array<String>) {
    val retryPolicy = ExponentialBackoffRetry(1000, 3)
    val zk = CuratorFrameworkFactory.builder()
            .connectString("192.168.11.128:2182,192.168.11.128:2183,192.168.11.128:2184")
            .sessionTimeoutMs(5000)
            .retryPolicy(retryPolicy)
            .namespace("curator")
            .build()
    zk.start()
    val selectorPath = "/master_selector"
    val selector = LeaderSelector(zk, selectorPath, LeaderSelectorListenerAdapter())
    selector.autoRequeue()
    selector.start()
    Thread.sleep(Long.MAX_VALUE)
}

class LeaderSelectorListenerAdapter : LeaderSelectorListener {
    override fun stateChanged(client: CuratorFramework?, newState: ConnectionState?) {
        if (newState == ConnectionState.LOST || newState == ConnectionState.SUSPENDED) {
            println("connection lost or suspended")
            throw CancelLeadershipException()
        }
    }

    override fun takeLeadership(client: CuratorFramework?) {
        println("成为了master" + LocalDateTime.now())
        Thread.sleep(3000 * 20)
        println("完成了master操作")
    }

}